﻿using System.Windows.Input;
using System.Device.Location;
using TaxiPlease.ViewModels;
using TaxiPlease.PhoneHelpers;
using System;
using System.Net;

namespace TaxiPlease
{
	public class MainViewModel : ViewModelBase
	{
		internal const string LocationDisabled = "Location service is disabled. Please enable it.";
		internal const string DataPlanDisabled = "Internet connection is disabled. Please enable it.";
		internal const string AddressDefault = "Address";
		private GeoCoordinate location;
		private string address = AddressDefault;
		private LocationService locationService;

		public MainViewModel()
		{
			Options = new OptionsViewModel();
			SendMessageCommand = new SendMessageCommand(this);
			CallCommand = new CallCommand(Options);
			Options.PropertyChanged += (s, e) =>
				{
					if (e.PropertyName == "IsLocationEnabled")
					{
						if (Options.IsLocationEnabled)
						{
							this.StartLocationService();
						}
						else
						{
							this.StopLocationService();
							this.Address = LocationDisabled;
						}
					}
				};
		}

		public ICommand SendMessageCommand
		{
			get;
			private set;
		}

		public GeoCoordinate Location
		{
			get
			{
				return location;
			}
			set
			{
				if (location != value)
				{
					location = value;
					this.RaisePropertyChanged("Location");
				}
			}
		}

		public string Address
		{
			get
			{
				return this.address;
			}
			set
			{
				if (this.address != value)
				{
					this.address = value;
					this.RaisePropertyChanged("Address");
				}
			}
		}

		public ICommand CallCommand
		{
			get;
			private set;
		}

		public OptionsViewModel Options
		{
			get;
			private set;
		}

		internal void StartLocationService()
		{
			if (Options.IsLocationEnabled)
			{
				if (locationService == null)
				{
					locationService = new LocationService();
					locationService.AddressChanged += (s, e) => this.Address = this.Address = string.IsNullOrEmpty(e.Address) ? LocationDisabled : e.Address;
					locationService.LocationChanged += (s, e) => this.Location = e.Location;
				}
				locationService.Start();
			}
			else
			{
				this.Address = LocationDisabled;
			}
		}

		internal void StopLocationService()
		{
			if (locationService != null)
			{
				locationService.Stop();
			}
		}
	}
}